<?php

namespace app\api\controller;

use app\api\library\Code;
use taoser\exception\ValidateException;
use taoser\Validate;
use think\helper\Str;

class BaseController
{

    /**
     * 是否批量验证
     * @var bool
     */
    protected $batchValidate = false;


    /**
     * 验证数据
     * @access protected
     * @param  array        $data     数据
     * @param  string|array $validate 验证器名或者验证规则数组
     * @param  array        $message  提示信息
     * @param  bool         $batch    是否批量验证
     * @return array|string|true
     * @throws ValidateException
     */
    protected function validate(array $data, $validate, array $message = [], bool $batch = false)
    {
        if (is_array($validate)) {
            $v = new Validate();
            $v->rule($validate);
        } else {
            if (strpos($validate, '.')) {
                // 支持场景
                [$validate, $scene] = explode('.', $validate);
            }
            $class = false !== strpos($validate, '\\') ? $validate : $this->parseClass('validate', $validate);
            $v     = new $class();
            if (!empty($scene)) {
                $v->scene($scene);
            }
        }
        $v->message($message);
        // 是否批量验证
        if ($batch || $this->batchValidate) {
            $v->batch(true);
        }

        return $v->failException(true)->check($data);
    }

    /**
     * 解析应用类的类名
     * @access public
     * @param string $layer 层名 controller model ...
     * @param string $name  类名
     * @return string
     */
    public function parseClass(string $layer, string $name): string
    {
        $name  = str_replace(['/', '.'], '\\', $name);
        $array = explode('\\', $name);
        $class = Str::studly(array_pop($array));
        $path  = $array ? implode('\\', $array) . '\\' : '';

        return 'app' . '\\' . $layer . '\\' . $path . $class;
    }

    /**
     * 成功返回
     * @param $data
     * @param $msg
     * @param $code
     * @return \support\Response
     */
    public function success($data = [], $msg = 'success', $code = Code::SUCCESS)
    {
        return json([
            'code'      => $code,
            'msg'       => $msg,
            'data'      => $data
        ]);
    }

    /**
     * 失败返回
     * @param $msg
     * @param $code
     * @param $data
     * @return \support\Response
     */
    public function fail($msg, $code = Code::FAILED, $data = [])
    {
        return json([
            'code'      => $code,
            'msg'       => $msg,
            'data'      => $data
        ]);
    }
}